$(function() {

    var placeholder = '请输入作品名称搜索作品';

    function formatBook(book) {
        if (book.loading) return book.name;

        var markup = "<div class='select2-result-repository clearfix'>" +
            "<div class='select2-result-repository__avatar'><img src='" + book.cover + "' /></div>" +
            "<div class='select2-result-repository__meta'>" +
            "<div class='select2-result-repository__title'>" + book.name + "（作者：" + book.author +  "）" + "</div>";

        if (book.description) {
            markup += "<div class='select2-result-repository__description'>" + book.description + "</div>";
        }

        markup += "</div></div>";

        // markup += "<div class='select2-result-repository__statistics'>" +
        //     "<div class='select2-result-repository__forks'> " + book.forks_count + "</div>" +
        //     "<div class='select2-result-repository__stargazers'> " + repo.stargazers_count + "</div>" +
        //     "<div class='select2-result-repository__watchers'> " + repo.watchers_count + "</div>" +
        //     "</div>" +
        //     "</div></div>";

        return markup;
    }

    function formatBookSelection(book) {
        if (book.name) return book.name + '_' + book.author;
        return book.text;
    }

    var $bookSelect2 = $('.select2.book').select2({
        placeholder: placeholder,
        allowClear: true,
        ajax: {
            url: '/book',
            dataType: 'json',
            delay: 250,
            data: function (params) {
                var query = {
                    keyword: params.term
                };
                return query;
            },
            processResults: function (data) {
                return {
                    results: data
                };
            },
            cache: false
        },
        escapeMarkup: function(markup) {
            return markup;
        },
        minimumInputLength: 0,
        templateResult: formatBook,
        templateSelection: formatBookSelection
    });
});
